<?php
class Admin_UseradminController extends Zendhlt_Controller_AdminAction {

	const ADMIN_ROLE = 1;
	const ACTIVE = 0;

	private $_currentUser;
	private $_arrParam;
	private $_paginator = array();
	private $_actionMain;
	private $_namespace;

	public function init() {
		$layoutPath = TEMPLATE_PATH . '/admin';
		$option = array('layout'     => 'index',
                   		'layoutPath' => $layoutPath);
		Zend_Layout::startMvc($option);

		// Phân trang
		$this->_paginator['itemCountPerPage'] = 5;
		$this->_paginator['pageRange'] 		  = 3;
		$this->_paginator['currentPage'] 	  = $this->_request->getParam('page', 1);

		// Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		// Duong dan cua Action chinh
		$this->_actionMain = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];

		// Dat ten SESSION
		// Luu cac du lieu filter vao SESSION
		$this->_namespace = $this->_arrParam['module'] . '-' . $this->_arrParam['controller'];
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if(empty($ssFilter->col) || ($this->_request->getParam('resetfilter', 0) == 1)) {
			$ssFilter->keywords 	= '';
			$ssFilter->col 			= 'ngay_tao';
			$ssFilter->order 		= 'DESC';
			$ssFilter->state 		= self::ACTIVE;
			$ssFilter->error 		= 0;
		}

		$this->_arrParam['paginator']			 = $this->_paginator;
		$this->_arrParam['ssFilter']['keywords'] = $ssFilter->keywords;
		$this->_arrParam['ssFilter']['col'] 	 = $ssFilter->col;
		$this->_arrParam['ssFilter']['order'] 	 = $ssFilter->order;
		$this->_arrParam['ssFilter']['state'] 	 = $ssFilter->state;

		// Truyen ra view
		$this->view->actionMain = $this->_actionMain;
		$this->view->currentController = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];
		$this->view->arrParam = $this->_arrParam;

		// Lay thong tin user admin hien tai
		$auth = Zend_Auth::getInstance();
		$this->_currentUser = $auth->getIdentity();
	}

	public function indexAction() {
		$this->view->headTitle('Danh sách user admin');

		$model = new Admin_Model_UsersAdminMapper();
		$paginator = new Zendhlt_Paginator();
		// Exclude current admin
		$exlude = implode(",", array($this->_currentUser->id));

		$users = $model->fetch($this->_arrParam, $exlude);
		$totalItem = $model->countItem($this->_arrParam, $exlude);

		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
		$this->view->totalItems = $totalItem;
		$this->view->Items = $users;

		// Display error if delete occur error {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		$this->view->msg = '';

		if ($ssFilter->error == 1) {
			$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện!';
			$ssFilter->error = 0;
		}
	}

	public function filterAction() {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		
		if ($this->_arrParam['type'] == 'search') {
			if($this->_arrParam['key'] == 1) {
				$ssFilter->keywords = trim($this->_arrParam['keywords']);
				$ssFilter->state = $this->_arrParam['state'];
			} else {
				$ssFilter->keywords = '';
				$ssFilter->state = self::ACTIVE;
			}
		}
		
		if ($this->_arrParam['type'] == 'order') {
			$ssFilter->col = $this->_arrParam['col'];
			$ssFilter->order = $this->_arrParam['by'];
		}
		
		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}
	
	private function compareDate($inputDate) {
		$maxDate = new DateTime("now");
		$maxDate->sub(new DateInterval('P18Y'));
		return $inputDate <= $maxDate;
	}

	public function addAction() {
		$this->view->headTitle('Thêm user admin');
	
		$form = new Admin_Form_UserAdmin();
		$this->view->form = $form;
		$this->view->msg = '';
	
		// Lấy dữ liệu từ bảng role add vào dropdownlist
		$modelGroup = new Admin_Model_RoleMapper();
		$itemGroup  = $modelGroup->fetchAll();
		if (count($itemGroup) > 0) {
			foreach($itemGroup as $key => $val) {
				if ($val->getId() != self::ADMIN_ROLE) {
					$key   = $val->getId();
					$value = $val->getTen_quyen_han();
					$form->role->addMultiOption($key, $value);
				}
			}
		}
	
		// Lấy dữ liệu từ bảng city add vào dropdownlist
		$cityMapper = new Admin_Model_ThanhPhoMapper();
		$cities		= $cityMapper->fetchAll();
		if (count($cities) > 0) {
			foreach($cities as $key => $val) {
				$key   = $val->getId();
				$value = $val->getTen();
				$form->thanh_pho_phu_trach->addMultiOption($key, $value);
			}
		}
	
		$mapper = new Admin_Model_UsersAdminMapper();
	
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
	
			if ($form->isValid($formData)) {
				$inputDate = date_create_from_format('d-m-Y', $form->getValue('ngay_sinh'));
				
				if ($this->compareDate($inputDate)) {
					$usersAdminInfo = new Admin_Model_TableColumn_UsersAdmin($formData);
					$usersAdminInfo->setId(0);
					$usersAdminInfo->setNguoi_tao($this->_currentUser ->id);
					$usersAdminInfo->setNguoi_cap_nhat($this->_currentUser->id);
					$usersAdminInfo->setPassword(Zendhlt_Encode::password($usersAdminInfo->getPassword()));
					
					if ($mapper->save($usersAdminInfo)) {
						$form->reset();
					} else {
						$this->view->msg = 'Xuất hiện lỗi trong quá trình thực hiện';
						$form->populate($formData);
					}
				} else {
					$form->ngay_sinh->addError('Chưa đủ 18 tuổi.');
					$form->populate($formData);
				}
			} else {
				$form->populate($formData);
			}
		}
	}
	
	// Update trang thai ẩn|hiện
	public function deleteAction() {
		$model = new Admin_Model_UsersAdminMapper();
	
		if (isset($this->_arrParam['id'])) {
			$id = $this->_arrParam['id'];
		} elseif (isset($this->_arrParam['cid'])) {
			$id = $this->_arrParam['cid'];
		}
	
		if ($id != null) {
			$state = $this->_arrParam['delete-type'];
	
			if ($model->deleteItems($id, $state, $this->_currentUser->id) == false) {
				$ssFilter = new Zend_Session_Namespace($this->_namespace);
				$ssFilter->error = 1;
			}
		}
	
		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}
	
	public function editAction() {
		$this->view->headTitle('Chỉnh sửa thông tin user admin');
		
		// Tạo form hiểm thị điền thông tin
		$form = new Admin_Form_UserAdmin();
		// Remove các trường không được phép sửa;
		$form->removeElement('password');
		$form->email->setAttribs(array('readonly' => 'readonly'));
		$form->email->clearValidators();
		
		$this->view->form = $form;
		$this->view->msg = '';
		
		// Lấy dữ liệu từ bảng role add vào dropdownlist
		$modelGroup = new Admin_Model_RoleMapper();
		$itemGroup  = $modelGroup->fetchAll();
		if (count($itemGroup) > 0) {
			foreach($itemGroup as $key => $val) {
				if ($val->getId() != self::ADMIN_ROLE) {
					$key   = $val->getId();
					$value = $val->getTen_quyen_han();
					$form->role->addMultiOption($key, $value);
				}
			}
		}
		
		// Lấy dữ liệu từ bảng city add vào dropdownlist
		$cityMapper = new Admin_Model_ThanhPhoMapper();
		$cities		= $cityMapper->fetchAll();
		if (count($cities) > 0) {
			foreach($cities as $key => $val) {
				$key   = $val->getId();
				$value = $val->getTen();
				$form->thanh_pho_phu_trach->addMultiOption($key, $value);
			}
		}
		
		$mapper = new Admin_Model_UsersAdminMapper();
		$arrData = $mapper->fetchAll('id=' . $this->_getParam('id', 0), 'edit');
		$data = array_shift($arrData);
		
		if ($data != null) {
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();
		
				if ($form->isValid($formData)) {
					$inputDate = date_create_from_format('d-m-Y', $form->getValue('ngay_sinh'));

					if ($this->compareDate($inputDate)) {
						$userAdmin = new Admin_Model_TableColumn_UsersAdmin($data);
						$userAdmin->setRole($form->getValue('role'));
						$userAdmin->setHo_ten($form->getValue('ho_ten'));
						$userAdmin->setNgay_sinh($form->getValue('ngay_sinh'));
						$userAdmin->setDien_thoai($form->getValue('dien_thoai'));
						$userAdmin->setThanh_pho_phu_trach($form->getValue('thanh_pho_phu_trach'));
						$userAdmin->setNguoi_cap_nhat($this->_currentUser->id);
						
						if ($mapper->save($userAdmin)) {
							$this->_redirect($this->_actionMain . '/index/page/' . $this->_paginator['currentPage']);
						} else {
							$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện.';
							$form->populate($formData);
						}
					} else {
						$form->ngay_sinh->addError('Chưa đủ 18 tuổi.');
						$form->populate($formData);
					}
				} else {
					$form->populate($formData);
				}
			} else {
				$data['ngay_sinh'] = date('d-m-Y', strtotime($data['ngay_sinh']));
				$form->populate($data);
			}
		} else {
			$this->view->msg = 'Dữ liệu không tồn tại trong database.';
		}
	}

}